﻿using Confluent.Kafka;
using Microsoft.Extensions.DependencyInjection;
using System.Text;

namespace Leo.Common.Kafka
{
    public static class DependencyInjectionExtension
    {
        public static KafkaBuilder AddKafka(this IServiceCollection services, KafkaSetting setting)
        {
            ServiceCollectionServiceExtensions.AddSingleton<KafkaSetting>(services, setting);
            return new KafkaBuilder(setting, services);
        }

        internal static string TryGetHeaderValue(this ConsumeResult<Ignore, string> result, string key)
        {
            string result2;
            try
            {
                string text = null;
                byte[] bytes;
                if (result != null && result.Message != null && result.Message.Headers != null && result.Message.Headers.TryGetLastBytes(key, out bytes))
                {
                    text = Encoding.UTF8.GetString(bytes);
                }
                result2 = text;
            }
            catch
            {
                result2 = null;
            }
            return result2;
        }
    }
}
